<?php

namespace App\Http\Controllers\Member;

use App\CustomTrait\StatusReturnTrait;
use App\CustomTrait\VerificationTrait;
use App\Model\Member;
use Illuminate\Http\Request;

class LoginController extends CommonController
{
  use VerificationTrait, StatusReturnTrait;

  public function index(Request $request)
  {
    if ($request->method() == 'POST') {
      $member = Member::where('tel', $request->get('tel'))->first();
      //验证手机号是否存在
      if (!$member) {
        return $this->error('error', '手机号不存在');
      } else if ($this->isCheckPassword($request->get('password'), $member)) {
        //验证登录密码
        return $this->error('error', '登录密码错误');
      } else if ($this->isCheckCode($request->get('code'))) {
        //验证验证码
        return $this->error('error', '验证码错误', 4000);
      } else {
        try {
          session(['member_id' => $member->id]);
          return $this->success(route('member.index'), '登录成功');
        } catch (\Exception $error) {
          return $this->error('error', '登录失败');
        }
      }
    } else {
      return view('member.login');
    }
  }

  /**
   * 退出登录
   * @return \Illuminate\Http\RedirectResponse
   */
  public function loginOut()
  {
    session()->flush();
    return redirect()->route('member.login');
  }
}
